// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/process/thread_debug_info.h>
#include <unistd.h>
#include <melon/experimental/symbolizer/signal_handler.h>
#include <turbo/log/logging.h>

namespace kumo::pollux::process {
    thread_local const ThreadDebugInfo *threadDebugInfo = nullptr;

    // Flag to ensure that printCurrentQueryId() only invokes the callback in
    // ThreadDebugInfo once. This is to prevent callback from being recursively
    // called in case it induces a fatal signal which ends up calling
    // printCurrentQueryId() again.
    thread_local bool fatalSignalProcessed = false;

    static void printCurrentQueryId() {
        const ThreadDebugInfo *info = GetThreadDebugInfo();
        if (info == nullptr) {
            const char *msg =
                    "Fatal signal handler. "
                    "ThreadDebugInfo object not found.";
            write(STDERR_FILENO, msg, strlen(msg));
        } else {
            const char *msg1 = "Fatal signal handler. Query Id= ";
            write(STDERR_FILENO, msg1, strlen(msg1));
            write(STDERR_FILENO, info->queryId_.c_str(), info->queryId_.length());
            const char *msg2 = " Task Id= ";
            write(STDERR_FILENO, msg2, strlen(msg2));
            write(STDERR_FILENO, info->taskId_.c_str(), info->taskId_.length());
            if (!fatalSignalProcessed && info->callback_) {
                fatalSignalProcessed = true;
                info->callback_();
            }
        }
        write(STDERR_FILENO, "\n", 1);
    }

    const ThreadDebugInfo *GetThreadDebugInfo() {
        return threadDebugInfo;
    }

    ScopedThreadDebugInfo::ScopedThreadDebugInfo(
        const ThreadDebugInfo &localDebugInfo)
        : prevThreadDebugInfo_(threadDebugInfo) {
        threadDebugInfo = &localDebugInfo;
    }

    ScopedThreadDebugInfo::ScopedThreadDebugInfo(
        const ThreadDebugInfo *localDebugInfo)
        : prevThreadDebugInfo_(threadDebugInfo) {
        if (localDebugInfo != nullptr) {
            threadDebugInfo = localDebugInfo;
        }
    }

    ScopedThreadDebugInfo::~ScopedThreadDebugInfo() {
        threadDebugInfo = prevThreadDebugInfo_;
    }

    void addDefaultFatalSignalHandler() {
        static bool initialized = false;
        if (!initialized) {
            melon::symbolizer::addFatalSignalCallback(&printCurrentQueryId);
            initialized = true;
        }
    }
} // namespace kumo::pollux::process
